package com.stars.easyms.rest.handler;

import com.stars.easyms.base.interceptor.AbstractEasyMsMethodInterceptor;
import com.stars.easyms.rest.bean.EasyMsRestContext;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInvocation;

/**
 * <p>className: EasyMsExceptionHandlerAspect</p>
 * <p>description: EasyMsExceptionHandlerAspect</p>
 *
 * @author guoguifang
 * @version 1.7.1
 * @date 2020/12/16 10:09 上午
 */
@Slf4j
public class EasyMsExceptionHandlerAspect extends AbstractEasyMsMethodInterceptor {

    @Override
    protected Object intercept(MethodInvocation methodInvocation) throws Throwable {

        //  获取EasyMsRestContext对象并判断是否为空，如果为空则跳过
        EasyMsRestContext easyMsRestContext = EasyMsRestSynchronizationManager.getEasyMsRestContext();
        if (easyMsRestContext == null) {
            return proceed(methodInvocation);
        }

        // 获取异常信息
        Throwable throwable = null;
        for (Object param: methodInvocation.getArguments()) {
            if (param != null && Throwable.class.isAssignableFrom(param.getClass())) {
                throwable = (Throwable) param;
                break;
            }
        }
        if (throwable != null) {
            easyMsRestContext.setThrowable(throwable);
        }

        // 执行请求过程
        Object result = proceed(methodInvocation);
        easyMsRestContext.setResponseBody(result);
        easyMsRestContext.setReturnResponseBody(true);
        return result;
    }

}